// utils.js
const fs = require('fs');
const path = require('path');
const Team = require('./team');  // 导入 Team 类

const readTeamsFromFile = (filename) => {
    const filePath = path.join(__dirname, filename);
    const data = fs.readFileSync(filePath, 'utf-8');  // 明确指定编码为 UTF-8
    const lines = data.trim().split('\n');
    const teams = [];

    for (const line of lines) {
        const [name, matchesPlayed, wins, draws, losses, goalsScored, goalsConceded, points] = line.split(',').map((value, index) =>
            index === 0 ? value : parseInt(value, 10)
        );
        const team = new Team(name);
        team.matchesPlayed = matchesPlayed;
        team.wins = wins;
        team.draws = draws;
        team.losses = losses;
        team.goalsScored = goalsScored;
        team.goalsConceded = goalsConceded;
        team.points = points;
        teams.push(team);
    }

    return teams;
};

const writeTeamsToFile = (teams, filename) => {
    const filePath = path.join(__dirname, filename);
    const data = teams.map(team => [
        team.name,
        team.matchesPlayed,
        team.wins,
        team.draws,
        team.losses,
        team.goalsScored,
        team.goalsConceded,
        team.points
    ].join(',')).join('\n');

    fs.writeFileSync(filePath, data, 'utf-8');  // 明确指定编码为 UTF-8
};

module.exports = { readTeamsFromFile, writeTeamsToFile };